/**
 * @module draggable
 * 拖动功能指令
*/
import Vue from 'vue'

Vue.directive('draggable', {
  bind(el, binding, vnode) {
    let dragging = false
    let dragStartPosition = null
    let dragStartMousePosition = null

    el.addEventListener('mousedown', (e) => {
      dragStartMousePosition = { x: e.clientX, y: e.clientY }
      dragStartPosition = { x: el.offsetLeft, y: el.offsetTop }
      dragging = true
    })

    document.addEventListener('mousemove', (e) => {
      if (dragging) {
        const dx = e.clientX - dragStartMousePosition.x
        const dy = e.clientY - dragStartMousePosition.y

        el.style.position = 'absolute'
        el.style.left = `${dragStartPosition.x + dx}px`
        el.style.top = `${dragStartPosition.y + dy}px`

        binding.value && binding.value({ x: dx, y: dy })
      }
    })

    document.addEventListener('mouseup', () => {
      dragging = false
    })
  }
})

